<template>
  <div class="control-panel">
    <div class="section-header">
      <div class="section-icon">🎮</div>
      <h2>控制面板</h2>
    </div>
    
    <div v-if="connectionStatus" class="connection-status" :class="connectionStatus.status">
      <div class="status-content">
        <span class="status-dot" :class="connectionStatus.status"></span>
        <span class="status-text">{{ connectionStatus.message }}</span>
      </div>
    </div>
    
    <div class="control-buttons">
      <button 
        @click="testConnection" 
        class="btn btn-test"
        :disabled="isRunning || isLoading"
      >
        <span class="btn-icon">{{ isLoading ? '⏳' : '🔍' }}</span>
        {{ isLoading ? '测试中...' : '测试连接' }}
      </button>
      
      <button 
        @click="toggleQuizSolver" 
        class="btn" 
        :class="isRunning ? 'btn-stop' : 'btn-start'"
      >
        <span class="btn-icon">{{ isRunning ? '⏹️' : '▶️' }}</span>
        {{ isRunning ? '停止解题' : '开始解题' }}
      </button>
    </div>
    
    <div class="status-summary">
      <div class="status-item">
        <span class="status-label">运行状态:</span>
        <span class="status-value" :class="isRunning ? 'running' : 'stopped'">
          {{ isRunning ? '运行中' : '已停止' }}
        </span>
      </div>
      <div class="status-item">
        <span class="status-label">连接状态:</span>
        <span class="status-value" :class="connectionStatus?.status || 'unknown'">
          {{ getConnectionStatusText() }}
        </span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useQuizStore } from '../store/quizStore'

const quizStore = useQuizStore()
const isRunning = ref(false)
const isLoading = ref(false)
const connectionStatus = ref(null)

// 状态映射表
const STATUS_MAP = {
  'success': '正常',
  'error': '错误',
  'warning': '警告',
  'pending': '检测中',
  'info': '信息'
}

// 更新连接状态
function updateConnectionStatus(status, message) {
  connectionStatus.value = { status, message }
}

onMounted(async () => {
  // 检查扩展是否已安装
  if (!chrome?.tabs) {
    updateConnectionStatus('error', '扩展未正确加载')
    return
  }
  
  // 检查解题器是否已运行
  await checkTabStatus()
})

// 检查当前标签页状态
async function checkTabStatus() {
  try {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true })
    
    if (!tabs?.[0]?.id) {
      updateConnectionStatus('error', '无法获取当前标签页信息')
      return
    }

    // 使用Promise包装chrome.tabs.sendMessage
    const response = await sendTabMessage(tabs[0].id, { action: 'getStatus' })
    
    if (!response) {
      updateConnectionStatus('error', '无法与内容脚本通信，请刷新页面后重试')
      return
    }
    
    isRunning.value = response.isRunning || false
    
    // 检查配置状态
    if (response.configs && !response.configs.modelConfig?.apiKey) {
      updateConnectionStatus('warning', '未配置API密钥，请先配置')
    } else {
      updateConnectionStatus('success', '连接正常')
    }
  } catch (error) {
    console.error('检查标签页状态出错:', error)
    updateConnectionStatus('error', `通信错误: ${error.message}`)
  }
}

// 发送消息到标签页并等待响应
function sendTabMessage(tabId, message) {
  return new Promise((resolve) => {
    try {
      chrome.tabs.sendMessage(tabId, message, (response) => {
        const error = chrome.runtime.lastError
        if (error) {
          console.warn('发送消息错误:', error)
          resolve(null)
          return
        }
        resolve(response)
      })
    } catch (error) {
      console.error('发送消息异常:', error)
      resolve(null)
    }
  })
}

// 切换解题状态
function toggleQuizSolver() {
  isRunning.value ? stopSolving() : startSolving()
}

// 开始解题
async function startSolving() {
  try {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true })
    
    if (!tabs?.[0]?.id) {
      updateConnectionStatus('error', '无法获取当前标签页信息')
      return
    }
    
    // 临时设置状态
    isRunning.value = true
    
    const response = await sendTabMessage(tabs[0].id, { action: 'startSolving' })
    
    if (!response) {
      updateConnectionStatus('error', '无法与内容脚本通信，请刷新页面后重试')
      isRunning.value = false
      return
    }
    
    if (!response.success) {
      updateConnectionStatus('error', response.error || '启动失败')
      isRunning.value = false
      return
    }
    
    updateConnectionStatus('success', '解题已开始')
  } catch (error) {
    console.error('启动解题出错:', error)
    updateConnectionStatus('error', `通信错误: ${error.message}`)
    isRunning.value = false
  }
}

// 停止解题
async function stopSolving() {
  try {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true })
    
    if (!tabs?.[0]?.id) {
      updateConnectionStatus('error', '无法获取当前标签页信息')
      return
    }
    
    const response = await sendTabMessage(tabs[0].id, { action: 'stopSolving' })
    
    if (!response) {
      updateConnectionStatus('error', '无法与内容脚本通信，请刷新页面后重试')
      return
    }
    
    isRunning.value = false
    updateConnectionStatus('info', '解题已停止')
  } catch (error) {
    console.error('停止解题出错:', error)
    updateConnectionStatus('error', `通信错误: ${error.message}`)
  }
}

// 测试连接
async function testConnection() {
  try {
    isLoading.value = true
    updateConnectionStatus('pending', '正在测试连接...')
    
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true })
    
    if (!tabs?.[0]?.id) {
      isLoading.value = false
      updateConnectionStatus('error', '无法获取当前标签页信息')
      return
    }
    
    const response = await sendTabMessage(tabs[0].id, { action: 'testConnection' })
    
    isLoading.value = false
    
    if (!response) {
      updateConnectionStatus('error', '无法与内容脚本通信，请刷新页面后重试')
      return
    }
    
    if (response.success) {
      updateConnectionStatus('success', '连接成功！')
    } else {
      updateConnectionStatus('error', `连接失败: ${response.error || '未知错误'}`)
    }
  } catch (error) {
    console.error('测试连接出错:', error)
    isLoading.value = false
    updateConnectionStatus('error', `通信错误: ${error.message}`)
  }
}

// 获取连接状态文本
function getConnectionStatusText() {
  if (!connectionStatus.value) return '未知'
  return STATUS_MAP[connectionStatus.value.status] || '未知'
}
</script>

<style>
.control-panel {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid rgba(102, 126, 234, 0.1);
}

.section-icon {
  font-size: 20px;
}

.section-header h2 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: #2c3e50;
}

.connection-status {
  margin-bottom: 16px;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
}

.connection-status.success {
  background: linear-gradient(135deg, #d4edda, #c3e6cb);
  color: #155724;
  border: 1px solid #c3e6cb;
}

.connection-status.error {
  background: linear-gradient(135deg, #f8d7da, #f5c6cb);
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.connection-status.warning {
  background: linear-gradient(135deg, #fff3cd, #ffeaa7);
  color: #856404;
  border: 1px solid #ffeaa7;
}

.connection-status.pending {
  background: linear-gradient(135deg, #d1ecf1, #bee5eb);
  color: #0c5460;
  border: 1px solid #bee5eb;
}

.connection-status.info {
  background: linear-gradient(135deg, #e2e3e5, #d6d8db);
  color: #383d41;
  border: 1px solid #d6d8db;
}

.status-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
}

.status-dot.success { background-color: #28a745; }
.status-dot.error { background-color: #dc3545; }
.status-dot.pending { background-color: #ffc107; }
.status-dot.warning { background-color: #fd7e14; }
.status-dot.info { background-color: #17a2b8; }

.status-text {
  flex: 1;
}

.control-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.btn {
  flex: 1;
  padding: 12px 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: all 0.2s ease;
}

.btn-test {
  background: #f8f9fa;
  color: #495057;
  border: 2px solid #e1e8ed;
}

.btn-test:hover:not(:disabled) {
  background: #e9ecef;
  border-color: #667eea;
  color: #667eea;
}

.btn-start {
  background: linear-gradient(135deg, #51cf66, #40c057);
  color: white;
  box-shadow: 0 4px 12px rgba(81, 207, 102, 0.3);
}

.btn-start:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(81, 207, 102, 0.4);
}

.btn-stop {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}

.btn-stop:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4);
}

.btn-icon {
  font-size: 14px;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
  box-shadow: none !important;
}

.status-summary {
  background: rgba(248, 249, 250, 0.8);
  border-radius: 8px;
  padding: 12px;
  border: 1px solid rgba(225, 232, 237, 0.5);
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 13px;
}

.status-item:last-child {
  margin-bottom: 0;
}

.status-label {
  color: #6c757d;
  font-weight: 500;
}

.status-value {
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.status-value.running { background: #d4edda; color: #155724; }
.status-value.stopped { background: #f8d7da; color: #721c24; }
.status-value.success { background: #d4edda; color: #155724; }
.status-value.error { background: #f8d7da; color: #721c24; }
.status-value.warning { background: #fff3cd; color: #856404; }
.status-value.pending { background: #d1ecf1; color: #0c5460; }
.status-value.unknown { background: #e2e3e5; color: #383d41; }
</style> 